package com.argticling.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.argticling.dao.impl.UserDAOImplementation;
import com.argticling.model.Article;
import com.argticling.model.Role;
import com.argticling.model.User;
import com.argticling.security.GrantedAuthorityImpl;
import com.argticling.service.ArticleService;
import com.argticling.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController extends MultiActionController {

	@Autowired
    private UserService userService;
	@Autowired
	private ArticleService articleService;
	
  @RequestMapping(value = "/emailAvailable", method = RequestMethod.GET)
  public ModelAndView emailAvailable(@RequestParam("userEmail") String username) {
	  boolean userExist = userService.userExist(username);
	  return new ModelAndView("/public/data", "data", !userExist);
  }
  
  @RequestMapping(value = "/getUserData", method = RequestMethod.GET)
  public ModelAndView getUserData(HttpServletRequest request) {
//	  String json = toJSONString(strength, life, name,agil,defense,lvl,exp,maxExp,maxLife,money,upgradePoints);
//
//      resp.setContentType("text/json");
//      PrintWriter writer = null;
//      try {
//          writer = resp.getWriter();
//          writer.write(json);
//      }
//      catch (IOException e) {
//          e.printStackTrace();
//      }
//finally {
//          writer.flush();
//          writer.close();
//      }
//
//  }


	  
	  
	  User user = userService.getUser(request.getRemoteUser());
	  System.out.println("holaaa");
	  return new ModelAndView("/public/data", "user", user);
  }

//	public String toJSONString(int strength, int life, String name,int agil, int defense, int lvl,int exp, int maxExp, int maxLife, int money, int upgradePoints) {
//		JSONObject json = new JSONObject();
//
//	    json.put("exp", exp);
//	    json.put("maxExp", maxExp);
//	    json.put("maxLife", maxLife);
//	    json.put("money", money);
//	    json.put("upgradePoints", upgradePoints);        
//	    json.put("lvl", lvl);
//	    json.put("name",name);
//	    json.put("life",life);
//	    json.put("strength", strength);
//	    json.put("agil", agil);
//	    json.put("defense", defense);
//
//	    return json.toString();
//	}
	
//	
//    @RequestMapping(value = "/user/contact/add", method = RequestMethod.POST)
//    public ModelAndView addContact(HttpServletRequest request, HttpServletResponse response) {
//       // Contact contact = (Contact) request.getAttribute(ParamConstants.CONTACT);
//        //userService.addContact(contact, contact.getId());
//        ModelAndView mav = new ModelAndView("");
//        return mav;
//    }


	//	
	// @RequestMapping(value = "/user/contact/add", method = RequestMethod.POST)
	// public ModelAndView addContact(HttpServletRequest request,
	// HttpServletResponse response) {
	// // Contact contact = (Contact)
	// request.getAttribute(ParamConstants.CONTACT);
	// //userService.addContact(contact, contact.getId());
	// ModelAndView mav = new ModelAndView("");
	// return mav;
	// }

	// @RequestMapping(value = "/privilege/add", method = RequestMethod.POST)
	// public ModelAndView addPrivilege(@RequestParam(ParamConstants.USER_ID)
	// String id,
	// @RequestParam(ParamConstants.SUPER_ADMIN) String superAdmin,
	// @RequestParam(ParamConstants.ADMIN) String admin,
	// @RequestParam(ParamConstants.ESCRITOR) String escritor,
	// @RequestParam(ParamConstants.COLUMNISTA) String columnista
	// ) {
	// if(superAdmin!=null){
	// userService.addPrivilege(new SuperAdminPrivilege(), id);
	// }
	// if(admin!=null){
	// userService.addPrivilege(new AdminPrivilege(), id);
	// }
	// if(escritor!=null){
	// userService.addPrivilege(new WritePrivilege(), id);
	// if(columnista!=null){
	// //falta comletar en dnd va la opcion de columnista con lo del twitter
	// }
	// }
	// ModelAndView mav = new ModelAndView("");
	// return mav;
	// }

	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public ModelAndView modifyUser(HttpServletRequest request, @RequestParam("userName") String userName,
			@RequestParam("userPassword") String password,
			@RequestParam("password_confirm") String passwordValidation,
			@RequestParam("userSurname") String surname,
			@RequestParam("userEmail") String email) {
		
		System.out.println("user.remoteUser : "+ request.getRemoteUser());
		System.out.println("user.name : "+userName);
		System.out.println("user.surname : "+surname);
		System.out.println("user.password : "+password);
		System.out.println("user.email : "+email);
		
		
		User user = userService.getUser(email);

		password = userService.encriptPass(password);

		user.setName(userName);
		user.setSurname(surname);
		user.setPassword(password);

		userService.persist(user);
		List<Article> articles = articleService.getLastArticles();
        ModelAndView mav = new ModelAndView("public/home");
        mav.addObject("articles", articles);
        mav.addObject("user", user);
        
		return mav;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView createUser(HttpServletRequest request,
			@RequestParam("userName") String userName,
			@RequestParam("userSurname") String userSurname,
			@RequestParam("userEmail") String email,
			@RequestParam("userPassword") String password) {
		String id = UUID.randomUUID().toString(); // todo falta crearlo...
		id.replace("-", "");
		User user = new User();
		user.setName(userName);
		user.setSurname(userSurname);
		System.out.println(userSurname);
		user.setId(id);
		password = userService.encriptPass(password);
		user.setPassword(password);
		user.setUsername(email);
		user.setRole(Role.WRITER.getName());
		userService.persist(user);
		
		Collection auth = new ArrayList();
		auth.add(new GrantedAuthorityImpl(Role.WRITER.getName()));		
		SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(email, password,auth));
		
		List<Article> articles = articleService.getLastArticles();
        ModelAndView mav = new ModelAndView("public/home");
        mav.addObject("articles", articles);
        mav.addObject("user", user);
		
		return mav;
	}

	// @RequestMapping(value = "/remove", method = RequestMethod.POST)
	// public ModelAndView removeContact(@RequestParam("userEmail") String mail)
	// {
	// System.out.println();
	// userService.delete(mail);
	// ModelAndView mav = new ModelAndView("public/home");
	// return mav;
	// }
	// @RequestMapping(value = "/privilege/remove", method = RequestMethod.POST)
	// public ModelAndView removePrivilege(@RequestParam(ParamConstants.USER_ID)
	// String id,
	// @RequestParam(ParamConstants.PRIVILEGE_ID) String privilegeId) {
	// userService.removePrivilege(privilegeId, id);
	// ModelAndView mav = new ModelAndView("");
	// return mav;
	// }
	//
	@RequestMapping(value = "/remove", method = RequestMethod.POST)
	public ModelAndView deleteUser(@RequestParam("userEmail") String mail) {
		System.out.println("delete user: "+mail);
		userService.delete(mail);
		ModelAndView mav = new ModelAndView("public/logoutSucessful");
		return mav;
	}

}
